//
//  LoadingView.swift
//  新浪微博项目
//
//  Created by 王炯 on 16/7/20.
//  Copyright © 2016年 王炯. All rights reserved.
//

import UIKit

//添加一条loading的直线
class LoadingView: UIProgressView
{
    
    //定义一个定时器，用于加载进度条
    var timer:NSTimer?
    
    //判断当前直线有没有在动
    var isAnim:Bool = false
    
    
    override init(frame: CGRect)
    {
        super.init(frame: CGRect(x: 0, y: 64, width: SCREENW, height: 5))
        
        //设置颜色
        self.tintColor = UIColor.blueColor()
    }
    
    required init?(coder aDecoder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }
    
    //从主控件中移除
    func removeLine()
    {
        removeFromSuperview()
    }
    
    //销毁时移除定时器
    deinit
    {
        print("line销毁了")
        timer?.invalidate()
    }
    
    
    //开始加载直线
    func startLoading()
    {
        isAnim = true
        self.hidden = false
        
        self.progress = 0
        
        //声明定时器，加载直线
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1/60, target: self, selector: #selector(LoadingView.ValueChanged), userInfo: nil, repeats: true)
    }
    
    //结束加载直线
    func endLoading()
    {
        isAnim = false
    }
    
    //直线的值改变
    func ValueChanged()
    {
        //正在加载直线时
        if isAnim
        {
            self.progress += 0.05
            
            if self.progress >= 0.95
            {
                self.progress = 0.95
            }
        }
        //当已经加载完成时
        else
        {
            //如果progress为1时
            if self.progress == 1
            {
                 self.hidden = true
                 //定时器移除
                timer?.invalidate()
            }
            else
            {
                self.progress += 0.05
            }
        }
    }
    

}
